﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.PersistenceObject.System;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.Menu.Interface;
using WMS.FC.Domain.Service.System;

namespace WMS.FC.Domain.Service.Menu
{
    public class DeleteMenuService : ServiceBase, IDeleteMenuService
    {
        protected readonly IMenuRepository menuRepository;

        public DeleteMenuService(ILogger<ServiceBase> logger, IOptions<WmsSettings> options, IMapper mapper, IMenuRepository menuRepository) : base(logger, options, mapper)
        {
            this.menuRepository = menuRepository;
        }

        public async Task<ActionResult<string>> DeleteMenu(string menuId, UserInfo userInfo)
        {
            var result = new ActionResult<string>("删除菜单");
            try
            {
                if (string.IsNullOrWhiteSpace(menuId))
                    return result.ArgumentError("请选择要删除的菜单");

                var menuPO = await menuRepository.FindById<MenuPO>(Convert.ToInt64(menuId));

                if (menuPO == null)
                    return result.PartSuccess("菜单已经删除");

                var count = await menuRepository.GetCount<MenuPO>(entity => entity.ParentId == menuPO.Id);
                if (count > 0)
                    return result.BusinessError("存在子菜单,不能删除该菜单");

                count = await menuRepository.Delete<MenuPO>(menuPO.Id);
                if (count == 0)
                    return result.DbError("删除菜单异常");

                result.Data = menuPO.ParentId.HasValue ? menuPO.ParentId.ToString() : "0";
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }
    }
}
